package com.amir.common.utils

import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.webkit.MimeTypeMap
import java.io.File
import java.util.*


object Tools {

    private fun getSuffix(file: File?): String? {
        if (file == null || !file.exists() || file.isDirectory) {
            return null
        }
        val fileName = file.name
        if (fileName == "" || fileName.endsWith(".")) {
            return null
        }
        val index = fileName.lastIndexOf(".")
        return if (index != -1) {
            fileName.substring(index + 1).toLowerCase(Locale.US)
        } else {
            null
        }
    }

    fun addMediaToLocalDb(context: Context, filePath: String): Uri? {
        return try {
            val file = File(filePath)
            val extension: String? = getSuffix(file)
            if (extension.isNullOrEmpty()) {
                return null
            }
            var type: String? =
                MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase())
            if (type.isNullOrEmpty()) {
                //android 4.4 webp无法解析
                when (extension) {
                    "webp" -> type = "image/webp"
                }
                if (type.isNullOrEmpty()) {
                    return null
                }
            }
            val values = ContentValues()
            values.put(MediaStore.MediaColumns.DATA, filePath)
            values.put(MediaStore.MediaColumns.TITLE, file.getName())
            values.put(MediaStore.MediaColumns.SIZE, file.length())
            values.put(MediaStore.MediaColumns.MIME_TYPE, type)
            values.put(MediaStore.Audio.Media.DISPLAY_NAME, file.getName())
            val uri: Uri
            uri = if (type.startsWith("audio")) {
                values.put(MediaStore.Audio.Media.ARTIST, "来自Y2002电音")
                //
                //  values.put(MediaStore.Audio.Media.DURATION, duration)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
                } else {
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                }
            } else if (type.startsWith("image")) {
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            } else if (type.startsWith("video")) {
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            } else {
                return null
            }
            val cursor: Cursor? = context.getContentResolver().query(
                uri,
                null,
                MediaStore.MediaColumns.DATA.toString() + "=?",
                arrayOf(filePath),
                null
            )
            val newUri = if (cursor != null && cursor.moveToFirst()) {
                val id: Long =
                    cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
                val localUri: Uri = Uri.withAppendedPath(uri, id.toString())
                context.contentResolver.update(localUri, values, null, null)
                ContentUris.withAppendedId(uri, id)
            } else {
                context.contentResolver.insert(uri, values)
            }
            cursor?.close()
            newUri
        } catch (e: Exception) {
            null
        }
    }

    fun installApp(context: Context, file: File?) {
        val intent = Intent(Intent.ACTION_VIEW)
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val apkUri: Uri = FileProviderUtils.getUriForFile(context, file)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
        }
        context.startActivity(intent)
    }
}